<?php

namespace App\Providers;

use App\Models\User;
use Illuminate\Support\ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Boot the authentication services for the application.
     *
     * @return void
     */
    public function boot()
    {
        $this->app['auth']->viaRequest('api', function ($request) {
            $encryptText = $request->cookie('login_user');
            if (!$encryptText) {
                return;
            }

            $decrypted = decrypt($encryptText);
            if (!$decrypted) {
                return;
            }

            [$userId, $lastLoginTime, $thisLoginTime] = explode('|', $decrypted);

            if ($thisLoginTime < time() - 3600 * 8) {
                return;
            }

            $user = User::find($userId);
            if (!$user || $user->login_time != $thisLoginTime) {
                return;
            }

            $user->lastLoginTime = $lastLoginTime;

            return $user;
        });
    }
}
